package com.boxing.servlet;

import com.boxing.bean.RespContent;
import com.boxing.bean.Stu;
import com.boxing.service.StuService;
import com.google.gson.Gson;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "StuMangerServlet", value = "/login/StuMangerServlet")
public class StuMangerServlet extends BaseServlet {
    private StuService stuService = new StuService();

    /**
     * 查询所有的学生
     */
    private void queryAllStu(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        List<Stu> stus = stuService.queryAllStu();
        response.getWriter().print(new Gson().toJson(stus));
    }


    /**
     * 修改学生信息
     */
    private void editStu(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        String phone = request.getParameter("phone");
        String sex = request.getParameter("sex");
        String sno = request.getParameter("sno");
        Stu stu = new Stu(sno, name, sex, phone);
        int i = 0;
        try {
            i = Integer.parseInt(id);
        }catch (Throwable e){
            e.printStackTrace();
        }
        RespContent respContent = new RespContent<>();
        if (i <=0){
            // 异常情况,需要响应客户端 失败的操作
            respContent.setCode(40);
            respContent.setMsg("异常,请稍后重试!");
        }else {
            stu.setId(i);
            boolean result = stuService.editStu(stu);
            if (result){
                // 修改成功, 响应客户端
                respContent.setCode(20);
                respContent.setMsg("修改成功!");
            }else {
                // 请客户端重试
                respContent.setCode(30);
                respContent.setMsg("修改失败,请稍后重试!");
            }
        }
        response.getWriter().print(new Gson().toJson(respContent));
    }

    /**
     * 新增学生
     */
    private void newStu(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
